package com.dh.api.gateway.filter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

import org.springframework.stereotype.Component;

import com.dh.api.gateway.exception.RateLimiterException;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;

/**
 * 限流拦截器
 * 
 * @author 作者 dinghao
 * @version 创建时间：2018年11月20日 上午11:55:33
 * @Description 类说明 : 限流
 */
@Component
public class RateLimiterFilter extends ZuulFilter {

	// 每秒放的令牌数
	private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);

	@Override
	public String filterType() {
		return PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return SERVLET_DETECTION_FILTER_ORDER - 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		if (!RATE_LIMITER.tryAcquire()) {
			throw new RateLimiterException();
		}
			return null;
	}

}
